<template>
  <a-card>
    <!-------------- 上方表单 -------------->
    <a-form-model
      :model="queryform"
      v-bind="layout"
      :rules="rules"
      ref="ruleForm"
    >
      <div style="margin-bottom: 3%">
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24"></a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="center">
            <span style="font-size: 150%">产成品形态转换</span>
          </a-col>
        </a-row>
      </div>
      <a-row>
        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" ref="document" prop="document">
            <a-input disabled v-model="queryform.document" />
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            ref="document_date"
            prop="document_date"
          >
            <a-date-picker
              @change="changeAllDate"
              style="width: 100%"
              v-model="queryform.document_date"
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" ref="housename" prop="housename">
            <a-select
              showSearch
              placeholder="请选择仓库"
              @change="changeWarhouse"
              v-model="queryform.housename"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotId + '|' + item.depotName"
                >{{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="部门">
            <a-tree-select
              v-model="queryform.department"
              allow-clear
              showSearch
              :tree-data="departmentList"
              :replace-fields="replaceFields"
              @change="onChangeBumen"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务员">
            <a-select
              v-model="queryform.salesmanName"
              showSearch
              @change="getsalesman"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="8" :lg="12" :md="8" :sm="24" :xs="24">
          <a-form-model-item
            label="库存组织"
            ref="kucunzuzhi"
            prop="kucunzuzhi"
          >
            <a-select
              v-model="queryform.kucunzuzhi"
              style="width: 100%"
              @change="getpk_calbodyId"
            >
              <a-select-option
                v-for="(item, index) in kucunzuzhiList"
                :key="index"
                :value="item.pkCalbody"
                >{{ item.bodycode }} {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <a-input
              style="width: 260%"
              placeholder
              v-model="queryform.remarks"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-------------- 单据表格 -------------->
      <a-table
        :columns="columns"
        :data-source="data"
        :scroll="{ x: 2000 }"
        :pagination="false"
      >
        <!-- 收发类别可编辑插槽  -->
        <span slot="sarType" slot-scope="text, record">
          <a-select v-model="record.sarType" style="width: 100%" showSearch>
            <a-select-option
              v-for="item in sarTypeList"
              :key="item.value"
              :value="item.value + '|' + item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 形态转换类别  -->
        <span slot="type" slot-scope="text, record">
          <a-select v-model="record.type" style="width: 100%" showSearch>
            <a-select-option
              v-for="item in changeTypeList"
              :key="item.value"
              :value="item.value + '|' + item.text"
              >{{ item.text }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 存货编码可编辑插槽  -->
        <span slot="inventoryName" slot-scope="text, record">
          <a-select
            v-model="record.inventoryName"
            style="width: 100%"
            @search="handleSearch"
            @focus="getKeyForInventorySearch(record.key)"
            @change="getInventoryInfo(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in record.goodsList"
              :key="item.inventory_id"
              :value="
                item.inventory_id +
                '|' +
                item.inventory_no +
                '|' +
                item.inventory_name +
                '|' +
                item.invspec +
                '|' +
                item.measname
              "
              >{{ item.inventory_no }} {{ item.inventory_name }}
              {{ item.invspec }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 辅助单位 -->
        <span slot="auxiliaryUnit" slot-scope="text, record">
          <a-select
            v-model="record.auxiliaryUnit"
            style="width: 100%"
            showSearch
          >
            <a-select-option
              v-for="item in Auxiliary_Unitlist"
              :key="item.value"
              :value="item.value"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </span>

        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number
            v-model="record.quantity"
            style="width: 100%"
            :precision="3"
          />
        </span>

        <!-- 金额 -->
        <span slot="amount" slot-scope="text, record">
          <a-input-number
            v-model="record.amount"
            style="width: 100%"
            :precision="2"
          />
        </span>
        <!-- 批次号可编辑插槽 -->
        <span slot="batchNo" slot-scope="text, record">
          <a-select v-model="record.batchNo" style="width: 100%" showSearch>
            <a-select-option
              v-for="(item, index) in record.batchList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </span>
        <!-- 转库日期可编辑插槽 -->
        <span slot="transferDate" slot-scope="text, record">
          <a-date-picker v-model="record.transferDate" />
        </span>
        <!-- 备注可编辑插槽 -->
        <span slot="remarks" slot-scope="text, record">
          <a-input v-model="record.remarks" />
        </span>
        <span slot="options" slot-scope="text, record">
          <a href="#" @click="cancle(record.key)">取消</a>
        </span>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
      <!-------------- 表格下方输入框 -------------->
      <div style="margin-top: 2%">
        <a-row>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24" align="left">
            <a-form-model-item label="审核人" ref="reviewer" prop="reviewer">
              <a-select showSearch placeholder v-model="queryform.reviewer">
                <a-select-option
                  v-for="item in chargeList"
                  :key="item.userId"
                  :value="item.userId + '|' + item.userName"
                  >{{ item.userName }}</a-select-option
                >
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期">
              <a-date-picker
                style="width: 100%"
                v-model="queryform.balance"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <a-input disabled v-model="queryform.single_producer"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div style="margin-top: 2%">
          <center>
            <a-button type="primary" @click="save" style="margin-right: 2%"
              >保存</a-button
            >
            <a-button disabled style="margin-right: 2%">审核</a-button>
            <a-button type="primary" disabled>提交</a-button>
          </center>
        </div>
      </div>
    </a-form-model>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax();

import { XingTaiZhuanHuanLieBiao } from "@/services/modules/KuCunTiaoZheng/XingTaiZhuanHuanLieBiao.js";
const zhuanhuanliebiaohttp = new XingTaiZhuanHuanLieBiao();

import { XingTaiZhuanHuan } from "@/services/modules/KuCunTiaoZheng/XingTaiZhuanHuan.js";
const zhuanhuanhttp = new XingTaiZhuanHuan();

// 引入
import moment from "moment";
import "moment/locale/zh-cn";

const columns = [
  {
    title: "序号",
    dataIndex: "lineNo",
    key: "lineNo",
    align: "center",
    width: 200,
  },
  {
    title: "收发类别",
    dataIndex: "sarType",
    key: "sarType",
    align: "center",
    scopedSlots: { customRender: "sarType" },
    width: 200,
  },
  {
    title: "仓库名称",
    dataIndex: "housename",
    key: "housename",
    align: "center",
    width: 200,
  },
  {
    title: "转换类别",
    dataIndex: "type",
    key: "type",
    align: "center",
    width: 200,
    scopedSlots: { customRender: "type" },
  },

  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    scopedSlots: { customRender: "inventoryNo" },
    width: 200,
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    width: 500,
    scopedSlots: { customRender: "inventoryName" },
  },

  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
    width: 200,
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
    width: 200,
  },
  {
    title: "辅助单位",
    dataIndex: "auxiliaryUnit",
    key: "auxiliaryUnit",
    align: "center",
    scopedSlots: { customRender: "auxiliaryUnit" },
    width: 200,
  },
  {
    title: "数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
    width: 200,
  },
  {
    title: "单价",
    dataIndex: "unitPrice",
    key: "unitPrice",
    align: "center",
    width: 200,
  },
  {
    title: "金额",
    dataIndex: "amount",
    key: "amount",
    align: "center",
    scopedSlots: { customRender: "amount" },
    width: 200,
  },
  {
    title: "批次号",
    dataIndex: "batchNo",
    key: "batchNo",
    align: "center",
    scopedSlots: { customRender: "batchNo" },
    width: 200,
  },
  {
    title: "转库日期",
    dataIndex: "transferDate",
    key: "transferDate",
    align: "center",
    scopedSlots: { customRender: "transferDate" },
    width: 200,
  },
  {
    title: "备注",
    dataIndex: "remarks",
    key: "remarks",
    align: "center",
    scopedSlots: { customRender: "remarks" },
    width: 300,
  },
  {
    title: "操作",
    dataIndex: "options",
    key: "options",
    align: "center",
    scopedSlots: { customRender: "options" },
    width: 100,
  },
];

const data = [];

export default {
  data() {
    return {
      replaceFields: {
        children: "syncDepartmentFilesEntityList",
        title: "deptname",
        value: "pkDeptdoc",
      },
      // ----------- 通用变量 -----------
      // 审核相关
      checkTag: false, // 审核标志
      UpdateTag: false, // 修改标志
      alreadyCheckTag: false, // 没审核

      // ----------- 查询表单 -----------
      // 下拉框 仓库
      storageList: [],
      departmentList: [], //部门
      UserList: [], // 库管员列表
      rules: {
        document: [
          {
            required: true,
            message: "单据号不能为空！",
            trigger: "blur",
          },
        ],
        document_date: [
          {
            required: true,
            message: "单据日期不能为空！",
            trigger: "change",
          },
        ],
        housename: [
          {
            required: true,
            message: "仓库名称不能为空！",
            trigger: "blur",
          },
        ],
        reviewer: [
          {
            required: true,
            message: "审核人不能为空！",
            trigger: "blur",
          },
        ],
      },
      // 查询表单数据
      queryform: {
        document: "",
        document_date: "",
        housename: "",
        remarks: "",
        reviewer: "",
        kucunzuzhi: "",
        single_producer: this.$store.state.user.info.username,
        single_producer_id: this.$store.state.user.info.id,
        balance: "",
        deptId: "", //部门id
        pkCalbody: "", //库存组织id
      },

      empty_: true,

      // 表单的格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // ----------- 单据表格 -----------
      // 表头
      columns,
      kucunzuzhiList: [], //库存组织列表

      // 数据源
      data,

      // ----------- 可编辑数据下拉框 -----------
      // 收发类别
      sarTypeList: [],

      // 辅助单位
      Auxiliary_Unitlist: [],

      // 转换类型
      changeTypeList: [],
      goodsList: [],

      // ----------- 表格下方下拉框 -----------
      // 审核人下拉框
      chargeList: [],
    };
  },

  watch: {
    $route: function (to, form) {
      if (
        to.path == "/MorphologicalTransformation" &&
        form.path == "/MorphologicalTransformationList"
      ) {
        console.log("--------- 更新视图 组装  ----------");

        if (this.$route.query.Id) {
          this.getRouterParam();
        }
      }
    },
  },
  mounted() {
    this.judgeDocument(); //判断单据号是否为空

    // 初始化表格
    this.setDataSource();
    // 获取仓库
    this.getApplyStorage();
    // 辅助单位
    this.getAuxiliary_Unitlist();
    // 获取转换类别
    this.getChangeType();
    // 初始化表格内日期 为当日日期
    this.initializationDate();
    // 获取审核人
    this.getInspectorList();
    // 获取收发类别
    this.getSendReceiveList();
    // 获取单号
    this.getApplyOrder();
    // 获取路由参数
    this.getRouterParam();
    //获取库存组织列表
    this.getTransformationCodeName();
    //部门
    this.getDepartmentTree();
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.queryform.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    onChangeBumen(a) {
      console.log("a", a);
      let array = a.split("|");
      this.queryform.deptId = array[0];
      // this.Form.deptIdName = array[1];
    },

    // 获取库存组织Id
    getpk_calbodyId(value) {
      console.log("这是value啊啊啊", value);
      // let array = value.split("|");
      this.queryform.pkCalbody = value;
      console.log("this.queryform.pkCalbody", this.queryform.pkCalbody);
    },
    // ----------- 通用 -----------
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=XTZH-";
      comHttp.getOrder(queryPath).then((res) => {
        this.queryform.document = res.message;
      });
    },

    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);

      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 根据路由传递id初始化表单信息
    setInitInfo(id) {
      zhuanhuanliebiaohttp
        .getWarhouseMorphologicalTransformationList(
          `?id=${id}&pageSize=200&pageNo=1`
        )
        .then(async (res) => {
          console.log("----- routerListRes -----", res);
          let getData = res.result.records[0];
          this.queryform.id = getData.id;
          this.queryform.document = getData.document;
          this.queryform.document_date = getData.documentDate;
          this.queryform.housename =
            getData.depotId + "|" + getData.depotId_dictText;
          this.queryform.remarks = getData.headRemark;
          this.queryform.reviewer =
            getData.reviewer + "|" + getData.reviewer_dictText;
          this.queryform.single_producer = getData.preparedBy_dictText;
          this.queryform.single_producer_id = getData.preparedBy;
          // 将数据赋值给表格
          let array = res.result.records;
          let resArray = [];
          for (let i = 0; i < array.length; i++) {
            let singleData = {
              key: i + 1,
              lineNo: i + 1,
              id: array[i].twoId, // id
              sarType:
                array[i].sendAndReceiveCategory +
                "|" +
                array[i].sendAndReceiveCategory_dictText, // 收发类别
              type:
                array[i].transformationType +
                "|" +
                array[i].transformationType_dictText, // 转换类别
              inventoryId: array[i].inventoryId, // 存货id
              inventoryNo:
                array[i].inventoryNo + "|" + array[i].inventoryId_dictText, // 存货编码
              inventoryName: array[i].inventoryId_dictText, // 存货名称
              invspec: array[i].invspec, // 规格型号
              auxiliaryUnit: array[i].auxiliaryUnit_dictText, // 辅助单位
              measname: array[i].measname, //单位
              quantity: array[i].number, // 数量
              amount: array[i].money, // 金额
              hourseId: array[i].depotId, // 仓库id
              housename: array[i].depotId_dictText, // 仓库名称
              batchNo: array[i].batch, // 批次号
              transferDate: array[i].documentDate, // 转库日期
              remarks: array[i].remark, // 备注
              // goodsList: await this.getInventoryCode(),
              batchList: await this.getBatchNumberList(
                array[i].inventoryId,
                array[i].depotId
              ),
            };
            resArray.push(singleData);
          }
          this.UpdateTag = false;
          this.data = resArray;
        });
    },

    // 转换undefined
    turnUndefined(option) {
      if (option === undefined) option = "";
      return option;
    },

    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    /*   
    当移入鼠标焦点时，获得当前列的key值，进行储存
    便于对某一行中的goodsList进行操作 
    */
    getKeyForInventorySearch(key) {
      this.currentKey = key;
    },

    // 模糊查询 存货编码
    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];

      console.log("value", value);
      let query = "?name=" + value;
      // 使用正则表达式 判断输入的字符中是否有空格
      let reg = /^\s*(\S+)\s*$/;
      // 若有 则去空格
      if (reg.test(value)) value = RegExp.$1;
      // 若没有 全是空格 则置空
      else value = "";
      // console.log("query", query);
      if (value == "" || value == null) {
        this.goodsList = [];
      } else {
       await comHttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].invspec == "null" ||
              res.result[i].invspec == null
            ) {
              res.result[i].invspec = "";
            }
            if (
              res.result[i].measname == "null" ||
              res.result[i].measname == null
            ) {
              res.result[i].measname = "";
            }
            let data = {
              inventory_id: res.result[i].pkInvbasdoc,
              inventory_no: res.result[i].invcode,
              inventory_name: res.result[i].invname,
              invspec: res.result[i].invspec,
              measname: res.result[i].measname,
            };
            goodsList_invname.push(data);

              //measname  dawnei minghceng
              //invspec 规格 invtype 型号
            }
          });

        let queryInventoryBySpec = "?invspec=" + value;
        //规格型号模糊查询
        await comHttp
          .getqueryInventoryBySpec(queryInventoryBySpec)
          .then((res) => {
            console.log("结果规格型号模糊查询", res);

            for (let i = 0; i < res.result.length; i++) {
              let data = {
                inventory_id: res.result.list[i].pkInvbasdoc, // 存货 id
                inventory_no: res.result.list[i].invcode, //存货编码
                inventory_name: res.result.list[i].invname, //存货名称
                invspec: res.result.list[i].invspec, //规格型号
                measname: res.result.list[i].measname, //单位
              };
              goodsList_invspec.push(data);
            }
          });
        //todo 合并去重函数
        await this.mergeArray(goodsList_invname, goodsList_invspec);
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventory_id)) {
          map.set(item.inventory_id, item);
        }
      }
      this.goodsList = [...map.values()]; //将

      this.$set(this.data[this.currentKey - 1], "goodsList", this.goodsList);
    },

    //返回库存组织编码和名称
    getTransformationCodeName() {
      zhuanhuanhttp.getTransformationCodeName().then((res) => {
        console.log("库存组织", res);
        this.kucunzuzhiList = res.result;
      });
    },

    // 查询人员信息列表
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              userName: res.result.list[i].username,
              userId: res.result.list[i].id,
              workNo: res.result.list[i].workNo,
            };
            this.UserList.push(data);
          }
        });
      }
    },

    // 获取存货编码和存货信息
    // getInventoryCode() {
    //   return new Promise((resolve) => {
    //     let _list = [];
    //     comHttp.getInventoryInformation().then((res) => {
    //       let array = res.result;
    //       console.log("----- arrayIn -----", array);
    //       for (let i = 0; i < array.length; i++) {
    //         let singleData = {
    //           inventory_id: array[i].id,
    //           inventory_no: array[i].inventoryNo,
    //           inventory_name: array[i].inventoryName,
    //           specificationsModel: array[i].specificationsModel,
    //           unit: array[i].unit,
    //         };
    //         _list.push(singleData);
    //       }
    //       resolve(_list);
    //     });
    //   });
    // },

    // 获取转换类别
    getChangeType() {
      comHttp.getWarehouseTransferType().then((res) => {
        console.log("----- typeRes -----", res);
        this.changeTypeList = res.result;
      });
    },

    // 获取辅助单位
    getAuxiliary_Unitlist() {
      comHttp.getAuxiliaryUnit().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            title: res.result[i].title,
            value: res.result[i].value,
          };
          this.Auxiliary_Unitlist.push(data);
        }
        // console.log("获取辅助单位列表::::",  this.Auxiliary_Unitlist);
      });
    },
    getsalesman(data) {
      let array = data.split("|");
      this.queryform.salesman = array[2];
      this.queryform.salesmanName = array[1];
      this.queryform.cbizid = array[2];
      console.log("this.Form.cbizid ", this.queryform.cbizid);
      console.log("this.Form.salesman ", this.queryform.salesman);
    },

    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.chargeList.push(data);
        }
      });
    },

    // 获取批次号
    getBatchNumberList(invId, depotId) {
      let temp = [];
      return new Promise((resolve) => {
        comHttp
          .getgetBatchNumberById(
            "?depotId=" + depotId + "&inventoryId=" + invId
          )
          .then((res) => {
            console.log("获取批次号res", res);
            temp = res.result;
            resolve(temp);
          });
      });
    },
    getDepartmentTree() {
      comHttp.getDepartmentList().then((res) => {
        if (res.success) {
          console.log("获取部门树", res);
          let resetRes = res.result;
          this.departmentList = resetRes;
        }
      });
    },

    // 获取收发类别列表
    getSendReceiveList() {
      this.sarTypeList = [];
      comHttp.getReceiveSendTypeListAll().then((res) => {
        console.log("收发类别列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].id,
            title: res.result[i].name,
          };
          this.sarTypeList.push(data);
        }
      });
    },

    // ----------- 标题旁按钮触发函数 -----------
    // 保存
    save(e) {
      console.log("----- saveE -----", e);
      if (!this.updateTag) {
        this.addWarhouseTransfer();
        // this.retundata();
      } else {
        console.log("----- 更新表单 -----");
        this.updateWarhouseTransfer();
      }
    },

    // 新增数据
    addWarhouseTransfer() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let _list = [];
          let entityData = {};
          this.checkempty(); //校验
          for (let i = 0; i < this.data.length; i++) {
            if ((i + 1) % 2 !== 0) {
              // 若没有存货编码 则不存此列
              if (this.data[i].inventoryId !== undefined) {
                console.log("this.data[i].type", this.data[i].type);
                let entityOne = {
                  conversionId: this.data[i].type.split("|")[0],
                  batch: this.data[i].batchNo,
                  depotId: this.queryform.housename.split("|")[0],
                  inventoryId: this.data[i].inventoryId,
                  money: this.data[i].amount,
                  number: this.data[i].quantity,
                  remark: this.data[i].remarks,
                  sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
                  transferDate: moment(this.data[i].transferDate).format(
                    "YYYY-MM-DD"
                  ),
                  auxiliaryUnit: this.data[i].auxiliaryUnit,
                  transformationType: this.data[i].type.split("|")[0],
                };
                entityData.entityOne = entityOne;
              }
            } else {
              if (this.data[i].inventoryId !== undefined) {
                let entityTwo = {
                  conversionId: this.data[i].type.split("|")[0],
                  batch: this.data[i].batchNo,
                  depotId: this.queryform.housename.split("|")[0],
                  inventoryId: this.data[i].inventoryId,
                  money: this.data[i].amount,
                  number: this.data[i].quantity,
                  remark: this.data[i].remarks,
                  sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
                  transferDate: moment(this.data[i].transferDate).format(
                    "YYYY-MM-DD"
                  ),
                  auxiliaryUnit: this.data[i].auxiliaryUnit,
                  transformationType: this.data[i].type.split("|")[0],
                };
                entityData.entityTwo = entityTwo;
              }
            }
            if (
              entityData.entityOne !== undefined &&
              entityData.entityTwo !== undefined
            ) {
              _list.push(entityData);
              entityData = {};
            }
          }
          console.log("----- _list -----", _list);
          let saveData = {
            balance: moment(this.queryform.document_date).format("YYYY-MM-DD"),
            auditMark: 2,
            bookkeepingMark: 2,
            depotId: this.queryform.housename.split("|")[0],
            deptId: "",
            document: this.queryform.document,
            documentDate: moment(this.queryform.document_date).format(
              "YYYY-MM-DD"
            ),
            list: _list,
            preparedBy: this.queryform.single_producer_id,
            remark: this.queryform.remarks,
            reviewer: this.queryform.reviewer.split("|")[0],
            reviewerDate: "",
            cdptid: this.queryform.deptId, //部门id
            cbizid: this.queryform.cbizid, //业务员id
            pkCalbody: this.queryform.pkCalbody, //库存组织id
            // inventoryName:this.record.inventoryName,//存货名称
            // quantity:this.record.quantity//数量
          };
          console.log("----- saveData -----", saveData);

          if (this.empty_ === true) {
            zhuanhuanhttp.postSaveWarhouseMor(saveData).then((res) => {
              console.log("----- saveRes -----", res);
              if (res.success) {
                this.$message.success("保存成功");
                this.ResetForm(); //重置
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          console.log("请把头部信息填写完整");
          this.$message.error("请把头部信息填写完整");
        }
      });
      // let _list = [];
      // let entityData = {};
      // for (let i = 0; i < this.data.length; i++) {
      //   if ((i + 1) % 2 !== 0) {
      //     // 若没有存货编码 则不存此列
      //     if (this.data[i].inventoryId !== undefined) {

      //       let entityOne = {
      //         conversionId: this.data[i].type.split("|")[0],
      //         batch: this.data[i].batchNo,
      //         depotId: this.queryform.housename.split("|")[0],
      //         inventoryId: this.data[i].inventoryId,
      //         money: this.data[i].amount,
      //         number: this.data[i].quantity,
      //         remark: this.data[i].remarks,
      //         sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
      //         transferDate: moment(this.data[i].transferDate).format(
      //           "YYYY-MM-DD"
      //         ),
      //         auxiliaryUnit: this.data[i].auxiliaryUnit,
      //         transformationType: this.data[i].type.split("|")[0],

      //       };
      //       entityData.entityOne = entityOne;
      //     }
      //   } else {
      //     if (this.data[i].inventoryId !== undefined) {
      //       let entityTwo = {
      //         conversionId: this.data[i].type.split("|")[0],
      //         batch: this.data[i].batchNo,
      //         depotId: this.queryform.housename.split("|")[0],
      //         inventoryId: this.data[i].inventoryId,
      //         money: this.data[i].amount,
      //         number: this.data[i].quantity,
      //         remark: this.data[i].remarks,
      //         sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
      //         transferDate: moment(this.data[i].transferDate).format(
      //           "YYYY-MM-DD"
      //         ),
      //         auxiliaryUnit: this.data[i].auxiliaryUnit,
      //         transformationType: this.data[i].type.split("|")[0],
      //       };
      //       entityData.entityTwo = entityTwo;
      //     }
      //   }
      //   if (
      //     entityData.entityOne !== undefined &&
      //     entityData.entityTwo !== undefined
      //   ) {
      //     _list.push(entityData);
      //     entityData = {};
      //   }
      // }
      // console.log("----- _list -----", _list);
      // let saveData = {
      //   auditMark: 2,
      //   bookkeepingMark: 2,
      //   depotId: this.queryform.housename.split("|")[0],
      //   deptId: "",
      //   document: this.queryform.document,
      //   documentDate: moment(this.queryform.document_date).format("YYYY-MM-DD"),
      //   list: _list,
      //   preparedBy: this.queryform.single_producer_id,
      //   remark: this.queryform.remarks,
      //   reviewer: this.queryform.reviewer.split("|")[0],
      //   reviewerDate: "",
      //   cdptid: this.queryform.deptId,//部门id
      //   cbizid:this.queryform.cbizid,//业务员id
      //   pkCalbody:this.queryform.pkCalbody,//库存组织id

      // };
      // console.log("----- saveData -----", saveData);

      // this.checkempty(saveData); //校验
      // if (this.empty_) {
      //   zhuanhuanhttp.postSaveWarhouseMor(saveData).then((res) => {
      //     console.log("----- saveRes -----", res);
      //     if (res.success) {
      //       this.$message.success("保存成功");
      //       this.ResetForm(); //重置
      //     } else {
      //       this.$message.error(res.message);
      //     }
      //   });
      // }
    },

    //校验是否为空
    checkempty() {
      this.empty_ = true;
      var message = []; //提示信息
      this.data.forEach((Res) => {
        console.log("Res", Res);
        if (Res.type == undefined) {
          this.empty_ = false;
          message.push("转换类别不能为空!      ");
        }
        if (!Res.inventoryNo) {
          this.empty_ = false;
          message.push("存货编码不能为空!      ");
        }
        if (Res.transferDate == "" || Res.transferDate == null) {
          this.empty_ = false;
          message.push("转库日期不能为空!      ");
        }
        if (Res.sarType == "" || Res.sarType == null) {
          this.empty_ = false;
          message.push("收发类别不能为空!      ");
        }
        if (Res.quantity == "" || Res.quantity == null) {
          this.empty_ = false;
          message.push("数量不能为空!      ");
        }
      });
      for (let i = 0; i < message.length; i++) {
        for (var j = i + 1; j < message.length; j++) {
          if (message[i] == message[j]) {
            message.splice(j, 1);
            j--;
          }
        }
      }
      if (!this.empty_) {
        this.$message.error(message);
      }
      // if (option.documentDate == "") {
      //   message.push("单据日期不能为空!" + "\xa0\xa0\xa0");
      //   this.empty_ = false;
      // }
      // if (option.depotId == "") {
      //   message.push("仓库名称不能为空!" + "\xa0\xa0\xa0");
      //   this.empty_ = false;
      // }
      // if (option.reviewer == "") {
      //   message.push("审核人不能为空!" + "\xa0\xa0\xa0");
      //   this.empty_ = false;
      // }
      // if (option.inventoryName== "") {
      //   message.push("存货名称不能为空!" + "\xa0\xa0\xa0");
      //   this.empty_ = false;
      // }
      // if (option.quantity == "") {
      //   message.push("数量不能为空!" + "\xa0\xa0\xa0");
      //   this.empty_ = false;
      // }
    },

    //保存重置表单
    ResetForm() {
      (this.queryform = {
        document: "",
        document_date: moment(this.queryform.document_date).format(
          "YYYY-MM-DD"
        ),
        housename: "",
        remarks: "",
        reviewer: "",
        single_producer: this.$store.state.user.info.username,
        single_producer_id: this.$store.state.user.info.id,
        balance: moment(this.queryform.document_date).format("YYYY-MM-DD"),
      }),
        this.setDataSource(); // 初始化表格 默认2行 出入库成对
      this.getApplyOrder(); //获取单据号
    },

    retundata() {
      this.queryform = {
        document: "",
        document_date: "",
        sarType: "",
        remarks: "",
        reviewer: "",
        single_producer: this.$store.state.user.info.username,
        single_producer_id: this.$store.state.user.info.id,
        balance: "",
      };
      this.data = [];
      this.getApplyOrder();
      this.initializationDate();
      this.setDataSource();
    },

    // 更新表单
    updateWarhouseTransfer() {
      let _list = [];
      let entityData = {};
      for (let i = 0; i < this.data.length; i++) {
        if ((i + 1) % 2 !== 0) {
          let entityOne = {
            conversionId: this.data[i].type.split("|")[0],
            batch: this.data[i].batchNo,
            depotId: this.queryform.housename.split("|")[0],
            inventoryId: this.data[i].inventoryId,
            money: this.data[i].amount,
            number: this.data[i].quantity,
            remark: this.data[i].remarks,
            sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
            transferDate: moment(this.data[i].transferDate).format(
              "YYYY-MM-DD"
            ),
            auxiliaryUnit: this.data[i].auxiliaryUnit,
            transformationType: this.data[i].type.split("|")[0],
            // transformationType: 0,
            // univalent: 0,
          };
          entityData.entityOne = entityOne;
        } else {
          let entityTwo = {
            conversionId: this.data[i].type.split("|")[0],
            batch: this.data[i].batchNo,
            depotId: this.queryform.housename.split("|")[0],
            inventoryId: this.data[i].inventoryId,
            money: this.data[i].amount,
            number: this.data[i].quantity,
            remark: this.data[i].remarks,
            sendAndReceiveCategory: this.data[i].sarType.split("|")[0],
            transferDate: moment(this.data[i].transferDate).format(
              "YYYY-MM-DD"
            ),
            auxiliaryUnit: this.data[i].auxiliaryUnit,
            transformationType: this.data[i].type.split("|")[0],
            // transformationType: 0,
            // univalent: 0,
          };
          entityData.entityTwo = entityTwo;
        }
        if (
          entityData.entityOne !== undefined &&
          entityData.entityTwo !== undefined
        ) {
          _list.push(entityData);
          entityData = {};
        }
      }
      console.log("----- _list -----", _list);
      let updateData = {
        id: this.queryform.id,
        auditMark: 2,
        bookkeepingMark: 2,
        depotId: this.queryform.housename.split("|")[0],
        deptId: "",
        document: this.queryform.document,
        documentDate: moment(this.queryform.document_date).format("YYYY-MM-DD"),
        list: _list,
        preparedBy: this.queryform.single_producer_id,
        remark: this.queryform.remarks,
        reviewer: this.queryform.reviewer.split("|")[0],
        reviewerDate: "",
        cdptid: this.queryform.deptId, //部门id
        cbizid: this.queryform.cbizid, //业务员id
        pkCalbody: this.queryform.pkCalbody, //库存组织id
      };
      console.log("----- updateData -----", updateData);
      zhuanhuanhttp.postUpdateWarhouseMor(updateData).then((res) => {
        console.log("----- saveRes -----", res);
        if (res.success) this.$message.success("更新成功");
        else this.$message.error("更新失败");
      });
    },

    // ----------- 上方输入框 -----------
    // 初始化日期
    initializationDate() {
      this.queryform.document_date = moment().format("YYYY-MM-DD");
      this.data = this.data.map((singleData) => ({
        key: singleData.key,
        lineNo: singleData.lineNo,
        transferDate: moment().format("YYYY-MM-DD"),
      }));
      this.queryform.balance = moment().format("YYYY-MM-DD");
    },
    //试试
    // 修改日期后 改变表格中所有日期
    changeAllDate(dateString) {
      console.log(
        "----- queryform.documentDate -----",
        this.queryform.document_date
      );
      this.queryform.balance = dateString;

      this.data.forEach((item, index) => {
        this.data[index].transferDate = dateString;
      });
      console.log("this.data", this.data);
    },

    // 点击仓库 改变表格内仓库
    async changeWarhouse() {
      const hourseName = this.queryform.housename.split("|")[1];
      const hourseId = this.queryform.housename.split("|")[0];
      for (let i = 0; i < this.data.length; i++) {
        this.$set(this.data[i], "housename", hourseName);
        this.$set(this.data[i], "hourseId", hourseId);
        // const _data = await this.getInventoryCode();
        // this.$set(this.data[i], "goodsList", _data);
      }
      console.log("----- Indata -----", this.data);
    },

    // ----------- 表格相关函数 -----------
    // 可编辑表格 获取存货信息
    async getInventoryInfo(key) {
      console.log("这是可编辑的表格", key);
      let target = this.data.filter((item) => item.key === key)[0];
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      console.log("array", array);
      this.$set(target, "inventoryId", array[0]); // 赋值给存货编码
      this.$set(target, "inventoryNo", array[1]); // 赋值给存货编码
      this.$set(target, "inventoryName", array[2]); // 赋值给存货名称

      let goodsInfomation = target.goodsList.filter(
        (item) => item.inventory_no === array[1]
      )[0];
      this.$set(target, "inventoryId", goodsInfomation.inventory_id); //赋值存货Id
      this.$set(target, "invspec", goodsInfomation.invspec); // 赋值规格型号
      this.$set(target, "measname", goodsInfomation.measname); // 赋值单位
      console.log(target);

      if (target.dischargeHouse) {
        const _list = await this.getBatchNumberList(
          target.inventoryId,
          target.dischargeHouse.split("|")[0]
        );
        this.$set(target, "batchList", _list);
      }

      // const _data = await this.getInventoryCode();
      // this.$set(target, "goodsList", _data);

      // let getNumberData = {
      //   depotId: this.queryform.inWarehouseId,
      //   inventoryId: goodsInfomation.inventory_id,
      // };

      // this.$set(
      //   target,
      //   "existingQuantity",
      //   await this.getTotalGoods(getNumberData)
      // ); // 存货编码
    },

    // 初始化表格 默认2行 出入库成对
    setDataSource() {
      let size = 2;
      this.data = [];
      for (let i = 0; i < size; i++) {
        let singleData = {
          key: i + 1,
          lineNo: i + 1,
          sarType: "", // 收发类别
          housename: "", //  仓库名称
          hourseId: "", // 仓库编码
          inventoryId: "", // 存货id
          inventoryNo: "", // , 存货编码
          inventoryName: "", // 存货名称
          invspec: "", // 规格型号
          measname: "", // 单位
          auxiliaryUnit: "", // 辅助单位
          quantity: "", // 数量
          unitPrice: "", // 单价
          amount: "", // 金额
          batchNo: "", // 批次号
          transferDate: "", // 转库日期
          remarks: "", // 备注
          goodsList: [], // 物品信息列
          batchList: [], // 批次号列
        };
        this.data.push(singleData);
        console.log(this.data);
      }
    },
    changeauxiliaryUnit(value) {
      console.log(value, 222222222);
    },
    // 表格添加新的记录
    newMember() {
      let pushDataForOne = {
        key: this.data.length + 1,
        lineNo: this.data.length + 1,
        sarType: "", // 收发类别
        housename: "", //  仓库名称
        hourseId: "", // 仓库编码
        inventoryId: "", // 存货id
        inventoryNo: "", // , 存货编码
        inventoryName: "", // 存货名称
        invspec: "", // 规格型号
        measname: "", // 单位
        auxiliaryUnit: "", // 辅助单位
        quantity: "", // 数量
        unitPrice: "", // 单价
        amount: "", // 金额
        batchNo: "", // 批次号
        transferDate: "", // 转库日期
        remarks: "", // 备注
        goodsList: [], // 物品信息列
        batchList: [], // 批次号列
      };
      let pushDataForTwo = {
        key: this.data.length + 2,
        lineNo: this.data.length + 2,
        sarType: "", // 收发类别
        housename: "", //  仓库名称
        hourseId: "", // 仓库编码
        inventoryId: "", // 存货id
        inventoryNo: "", // , 存货编码
        inventoryName: "", // 存货名称
        invspec: "", // 规格型号
        measname: "", // 单位
        auxiliaryUnit: "", // 辅助单位
        quantity: "", // 数量
        unitPrice: "", // 单价
        amount: "", // 金额
        batchNo: "", // 批次号
        transferDate: "", // 转库日期
        remarks: "", // 备注
        goodsList: [], // 物品信息列
        batchList: [], // 批次号列
      };
      if (this.data[this.data.length - 1].housename !== "") {
        pushDataForOne.housename = this.data[this.data.length - 1].housename;
        pushDataForOne.hourseId = this.data[this.data.length - 1].hourseId;
        pushDataForTwo.housename = this.data[this.data.length - 1].housename;
        pushDataForTwo.hourseId = this.data[this.data.length - 1].hourseId;
      }
      if (this.data[this.data.length - 1].transferDate !== "") {
        pushDataForOne.transferDate =
          this.data[this.data.length - 1].transferDate;
        pushDataForTwo.transferDate =
          this.data[this.data.length - 1].transferDate;
      }
      this.data.push(pushDataForOne);
      this.data.push(pushDataForTwo);
      this.$message.success("添加成功");
    },
    // 选择库存组织编码的change触发函数
    UnitNameChange(value, option) {
      this.formdata.id = option.key;
      // console.log(value , option);
      const newValue = value.split("|");
      console.log(newValue);
      this.formdata.bodycode = newValue[0];
      this.formdata.bodyname = newValue[1];
    },

    // 删除表格中的记录
    cancle(key) {
      // console.log(key);
      if (this.data.length > 2) {
        this.data.splice(key - 2, 2);
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留两行");
      }
    },
  },
};
</script>

<style></style>
